import os
import time

import jieba
import requests
import pandas as pd
from bs4 import BeautifulSoup


class Data_catcher:

    film_cid = None
    film_name = None
    barrage_dataset = None
    max_time = None
    name_replace_list = {"你的名字":"你的名字。", "哥斯拉2":"哥斯拉2：怪兽之王"}

    def __init__(self, film_name):
        if self.name_replace_list.get(film_name) is not None:
            self.film_name = self.name_replace_list[film_name]
        else:
            self.film_name = film_name
        self.get_film_cid()

    def get_film_cid(self):
        try:
            r = requests.get("https://search.bilibili.com/pgc?keyword=" + self.film_name, timeout=30)
            data = BeautifulSoup(r.text, "html.parser").select("[class='title']")
            url = "https:"+data[0].get('href')
            sub_data = BeautifulSoup(requests.get(url, timeout=30).text, "html.parser").find_all("script")
            for script in sub_data:
                if 'window.__INITIAL_STATE__' in str(script):
                    script1 = str(script).split('=')[1].split(",")
                    is_collect_right = False
                    for i in script1:
                        if "h1Title" in i and self.film_name in i:
                            is_collect_right = True
                            self.film_name = i.split(":")[1][1:-1]
                        if "cid" in i and is_collect_right:
                            self.film_cid = i.split(":")[1]
        except:
            self.film_cid = None

    def set_barrage_dataset(self):
        if os.path.exists('Datas/《' + self.film_name + '》弹幕整体数据.csv') is False:
            r = requests.get('http://comment.bilibili.com/' + self.film_cid + '.xml', timeout=30)
            comments = BeautifulSoup(str(r.content, 'utf-8'), 'xml').find_all('d')
            times_ = BeautifulSoup(str(r.content, 'utf-8'), 'xml').select('d')
            times = []
            maxt = 0
            for timestring in times_:
                t = int(float(str(timestring).split('"')[1].split(',')[0]))
                if t >= maxt:
                    maxt = t
                times.append(t)
            comments_dict = {'comments': [comment.text for comment in comments], 'time': times, str(maxt): ''}
            self.max_time = maxt
            pd_ = pd.DataFrame(comments_dict)
            pd_.sort_values(by=['time'], inplace=True)
            self.barrage_dataset = {'comments': pd_['comments'].tolist(), 'time': pd_['time'].tolist()}
            pd_.to_csv('Datas/《' + self.film_name + '》弹幕整体数据.csv', encoding='utf-8')
        else:
            pd_ = pd.read_csv('Datas/《' + self.film_name + '》弹幕整体数据.csv')
            self.barrage_dataset = {'comments': pd_['comments'].tolist(), 'time': pd_['time'].tolist()}
            self.max_time = int(pd_.columns[3])

    def get_barrage_ranking(self):

        def judgemeaningless(string):
            dic = ['这个', '那个', '什么', '没有', '就是', '真的', '不是', '一个']
            if string in dic:
                return True
            if len(set(string)) == 1:
                return True
            else:
                return False

        counts, speak = {}, ''
        for i in self.barrage_dataset['comments']:
            speak += i
        wordslist = jieba.lcut(speak)
        for word in wordslist:
            if judgemeaningless(word):
                del word
                continue
            else:
                counts[word] = counts.get(word, 0) + 1
        items = list(counts.items())
        items.sort(key=lambda x: x[1], reverse=True)
        return items[0:30]

    def get_barrage_time_data(self):
        timeruler, numbers = [], []
        i = 0
        while i <= self.max_time:
            timeruler.append(time.strftime("%H:%M:%S", time.localtime(i + 57600)))
            i += 600
            n = 0
            for x in self.barrage_dataset['time']:
                if (i - 600) < x <= i:
                    n += 1
                elif x > i:
                    break
            numbers.append(n)
        return timeruler, numbers
